package com.imooc.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/12/28 22:52
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>
{
    //用户记录和管理所有客户端的channel
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception
    {
        //获取客户端传输的消息
        String msgText = msg.text();
        System.out.println("接收到的数据: " + msgText);
//        for (Channel client : clients)
//        {
//            client.writeAndFlush(new TextWebSocketFrame("[服务器接收到的消息]"
//                    + LocalDateTime.now() + " 接收到的消息为: " + msgText));
//        }
        clients.writeAndFlush(new TextWebSocketFrame("[服务器接收到的消息]"
                + LocalDateTime.now() + " 接收到的消息为: " + msgText));
    }

    /**
     * @Description: 当客户端连接服务端之后, 获取到客户端的channel, 并且放到channelGroup中
     * @Param: ctx
     * @return:
     * @Author: 朝花不迟暮
     * @Date: 2020/12/28
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception
    {
        Channel channel = ctx.channel();
        clients.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception
    {
        System.out.println("长id: " + ctx.channel().id().asLongText());
        System.out.println("短id: " + ctx.channel().id().asShortText());
    }
}
